using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace RideMe.CommandManagement
{
    public class CommandManager : System.ComponentModel.Component
    {
        private CommandsCollection _commands;
        private Hashtable _hashCommandExecutors;   

        public CommandManager()
        {
            _commands = new CommandsCollection(this);
            _hashCommandExecutors = new Hashtable();

            // Setup idle processing
            Application.Idle += new EventHandler(Application_Idle);

            // By default, menus and toolbars are known
            RegisterCommandExecutor("System.Windows.Forms.ToolStripMenuItem", 
                                        new MenuCommandExecutor());

            RegisterCommandExecutor("System.Windows.Forms.ToolStripButton", 
                                        new ToolBarCommandExecutor());
        }


        public CommandsCollection Commands
        {
            get
            {
                return _commands;
            }
        }

        internal void RegisterCommandExecutor(string type, CommandExecutor executor)
        {
            _hashCommandExecutors.Add(type, executor);
        }

        internal CommandExecutor GetCommandExecutor(object instance)
        {
            return _hashCommandExecutors[instance.GetType().ToString()] as CommandExecutor;
        }


        private void Application_Idle(object sender, System.EventArgs e)
        {
            IDictionaryEnumerator myEnumerator =
                (IDictionaryEnumerator)_commands.GetEnumerator();

            while (myEnumerator.MoveNext())
            {
                Command cmd = myEnumerator.Value as Command;
                if (cmd != null)
                {
                    cmd.DoUpdate();
                }
            }
        }
    }
}
